var express = require('express')
var router = express.Router()
var multer  = require('multer')
const ipAdress=require("../../utils/getIPAdress")
// var upload = multer({ dest: 'public/images'})  //这种方式不够灵活
var fs = require("fs");
let path = require('path');
const PUBLIC_IMAGE_PATH = path.resolve(__dirname, '../../public/images');
const PUBLIC_FILE_PATH = path.resolve(__dirname, '../../public/files');
var userModel = require('../../database/model/userModel')
const midderJob=(res,req,next)=>{//判断文件夹是否存在
  const isExists=fs.existsSync(PUBLIC_IMAGE_PATH)
  const isExists2=fs.existsSync(PUBLIC_FILE_PATH)
  if(!isExists){//recursive 递归创建
    fs.mkdirSync(PUBLIC_IMAGE_PATH,{recursive:true},(err)=>{
      if(err) return console.error("目录创建失败",err)
    })
    console.log("images目录创建成功");
  }
  if(!isExists2){//recursive 递归创建
    fs.mkdirSync(PUBLIC_FILE_PATH,{recursive:true},(err)=>{
      if(err) return console.error("目录创建失败",err)
    })
    console.log("file目录创建成功");
  }
  next()
}
//验证
var storage = multer.diskStorage({
  destination: function (req, file, cb) {  //设定图片存储路径
    const imgTypeList='.bmp,.jpg,.jpeg,.png,.tif,.gif,.pcx,.tga,.exif,.fpx,.svg,.psd,.cdr,.pcd,.dxf,.ufo,.eps,.ai,.raw,.WMF,.webp,.avif,.apng'
    let fileType=file.mimetype.split('/')[1]
    if(imgTypeList.indexOf(fileType)>-1){
      cb(null,PUBLIC_IMAGE_PATH)
    }else{
      cb(null,PUBLIC_FILE_PATH)
    }
    // cb(null,__dirname, 'public/images')//这种本地也可以
    // cb(null, '../public/images')//线上的服务器 用相对路径会出错改用绝对路径后正确 用npm 启动服务器 相对路径又可以了
  },
  filename: function (req, file, cb) {  //设定图片自定义名称
    let fileName = Math.random().toString(36).substring(2)+Date.now(); //自定义生成随机图片名称
    let type = file.originalname.split('.')[1] //获取图片后缀
    cb(null, `${fileName}.${type}`)
  }
})

var upload = multer({ storage: storage })

router.post('/upload',midderJob,upload.single('file'),(req,res)=>{  //图片上传 //签发的fileName要和前端的upload上传组件二进制数据的key名保持一致
  const imgTypeList='.bmp,.jpg,.jpeg,.png,.tif,.gif,.pcx,.tga,.exif,.fpx,.svg,.psd,.cdr,.pcd,.dxf,.ufo,.eps,.ai,.raw,.WMF,.webp,.avif,.apng'
  let fileType=req.file.mimetype.split('/')[1]
  if(imgTypeList.indexOf(fileType)>-1){
    res.send({  //下发图片路径相关数据给前端
      code:1,
      msg:'图片上传成功',
      data:{
        imgurl:'http://'+`${ipAdress}`+`:3000/images/${req.file.filename}`,
        fileName:req.file.originalname
      }
    })
  }else{
    res.send({  //下发图片路径相关数据给前端
      code:1,
      msg:'文件上传成功',
      data:{
        fileUrl:'http://'+`${ipAdress}`+`:3000/files/${req.file.filename}`,
        fileName:req.file.filename,
        originalname:req.file.originalname
      }
    })
  }
})


module.exports=router